<?php
namespace app\jiyun\controller;

use app\common\model\admin\AccountModel;
use app\common\model\base\CountryModel;
use app\common\model\collect\OrderExpressModel;
use app\common\model\jiyun\TransporModel;
use app\common\model\jiyun\warehouse\WarehouseAbroadModel;
use app\common\model\jiyun\warehouse\WarehouseModel;
use app\common\model\shop\PlatformModel;
use app\jiyun\service\base\CommonService;
use think\admin\helper\QueryHelper;
use think\facade\Db;

class Transportation extends BaseController
{
    /**
     * 集运单
     * @auth true
     * @menu true
     * @return void
     */
    public function index ()
    {
        TransporModel::mQuery()->layTable(function () {
            $this->title = lang('集运单列表');

            // 仓库
            $this->warehouse_arr = CommonService::instance()->getWarehouse($this->account_id);
            // 获得目的国
            $this->country_arr = CommonService::instance()->getEndCountry();

            $this->status_arr    = TransporModel::getStatus();

        }, function (QueryHelper $query) {


            $query->with(['warehouse','account'])->order('id', 'desc');

            // 数据列表搜索过滤
            $query->equal('account_id,warehouse_id,status,to_country_id,to_warehouse_id')->like('trans_no,batch_no')->dateBetween('create_at');
        });
    }


    protected function _index_page_filter (&$data)
    {
        /*$common_service   = CommonService::instance();
        // 获得仓库
        $warehouse_arr    = $common_service->getWarehouse($this->account_id);
        // 获得平台
        $system_platform  = $common_service->getSystemPlatform();
        // 获得公司名字
        $account          = $common_service->getAccount();*/
        $status = TransporModel::getStatus();

        foreach ($data as &$item) {
            /*$item['warehouse_name'] = $warehouse_arr[$item['warehouse_id']] ?? '';*/
            $item['status_name']         = $status[$item['status']]  ?? '';
            $item['account_name']   = $item['account']['title']  ?? '';
            $item['warehouse_name'] = $item['warehouse']['warehouse_c_name']  ?? '';
        }
    }

    /**
     * 添加集运单
     * @auth true
     * @menu true
     * @return void
     */
    public function add()
    {
        // 获取国家列表
        $this->country_list = CountryModel::mq()->column('coun_c_name', 'id');
        $this->warehouse_list = WarehouseModel::mq()->column('warehouse_c_name', 'id');
        TransporModel::mForm();
    }

    /**
     * 查看集运单
     * @auth true
     * @menu true
     * @return void
     */
     public function detail()
     {
         $this->trans_id = $this->request->param('id', 0);
         $info = TransporModel::mq()->where(['id' => $this->trans_id])->find();

         $warehouse_info = WarehouseModel::mq()->where(['id' => $info['warehouse_id']])->find();
//         $country_info = CountryModel::mq()->where(['id' => $info['country_id']])->find();
//         $warehouse_abroad_info = WarehouseAbroadModel::mq()->where(['id' => $info['to_warehouse_id']])->find();

         $info['warehouse_name'] = $warehouse_info['warehouse_c_name'] ?? '';
//         $info['country_name'] = $country_info['title'] ?? '';
//         $info['warehouse_abroad'] = $warehouse_abroad_info['warehouse_c_name'] ?? '';

         $this->trans_info = $info;
         TransporModel::mForm();
     }

    /**
     * 获取海外仓列表仓库列表
     * @return void
     */
    public function getWarehouseAbroadList()
    {
        $country_id = $this->request->get('country_id', 0);
        $list = WarehouseAbroadModel::mq()->where(['country_id' => $country_id, 'status' => 1])->column('warehouse_c_name', 'id');
        $this->success(lang('仓库列表'), $list);
    }

    /**
     * 获取渠道列表
     * @return void
     */
    public function getChannelList()
    {
        $country_id = $this->request->get('country_id', 0);
        $list = WarehouseAbroadModel::mq()->where(['country_id' => $country_id, 'status' => 1])->column('warehouse_c_name', 'id');
        $this->success(lang('仓库列表'), $list);
    }

    /**
     * 查找或创建集运单号
     * @return void
     */
    public function createTransNo()
    {
        $params = $this->request->post();

        if(empty($params['trans_no'])) { // 生成新的集运单号
            $to_country_id = $params['to_country_id'] ?? 0;
            $to_warehouse_id = $params['to_warehouse_id'] ?? 0;
            // 获取国家信息
            $country_info = CountryModel::mq()->where(['id' => $to_country_id])->find();
            // 获取海外仓信息
            $warehouse_abroad_info = WarehouseAbroadModel::mq()->where(['id' => $to_warehouse_id])->find();

            $data = [
                'trans_no' => TransporModel::createTransporNo(),
                'account_id' => $this->account_id,
                'warehouse_id' => $params['warehouse_id'] ?? 0,
                'to_country_id' => $to_country_id,
                'to_country_name' => $country_info['coun_c_name'] ?? '',
                'to_warehouse_id' => $to_warehouse_id,
                'to_warehouse_name' => $warehouse_abroad_info['warehouse_c_name'] ?? '',
                'weight' => $params['weight'] ?? 0,
            ];

            $trans_id = TransporModel::mq()->insertGetId($data);
            if($trans_id) {
                $this->success(lang('集运单号创建成功'), ['trans_no' => $data['trans_no']]);
            } else {
                $this->error(lang('生成失败'), ['trans_no' => '']);
            }

        } else { // 查找集运单号
            $trans_info = TransporModel::mq()->where(['trans_no' => $params['trans_no']])->find();

            // 获取海外仓列表
            $warehouse_abroad_list = WarehouseAbroadModel::mq()->where(['country_id' => $trans_info['to_country_id']])->column('warehouse_c_name', 'id');

            $this->success(lang('查找成功'), ['trans_info' => $trans_info, 'warehouse_abroad_list' => $warehouse_abroad_list]);
        }
    }

    /**
     * 搜索包裹并添加到集运单中
     * @return void
     */
    public function searchPackageNo()
    {
        $package_no = $this->request->get('package_no', '');
        $trans_no = $this->request->get('trans_no', '');
        $info = OrderExpressModel::mq()->where(['foreign_express_no' => $package_no])->find(); // 5545432678 JY202412053
        $trans_info = TransporModel::mq()->where(['trans_no' => $trans_no])->find();
        if(empty($trans_info)) {
            $this->error(lang('集运单号不存在，请先创建集运单号'));
        }
        if($trans_info['status'] >= 3) {
            $this->error(lang('集运单已发货'));
        }
        if(empty($info)) {
            $this->error(lang('包裹不存在'));
        }
        if($trans_info['status'] >= 2) {
            $this->error(lang('包裹已经集包'));
        }

        // 启动事务
        Db::startTrans();
        try {
            // 将包裹添加到集运单中
            $result = OrderExpressModel::mq()->where(['id' => $info['id']])->update(['trans_id' => $trans_info['id']]);
            // 更新集运单信息
            $list = OrderExpressModel::mq()->where(['trans_id' => $trans_info['id']])->select()->toArray();
            $weight = 0;
            foreach ($list as $item) {
                $weight += $item['weight'] ?? 0;
            }
            TransporModel::mq()->where(['id' => $trans_info['id']])->update(['weight' => $weight, 'status' => 1]);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error(lang('添加失败') . '：' . $e->getMessage());
        }
        $this->success(lang('添加成功'));
    }

    /**
     * 获取集运单下的包裹
     * @return \think\response\Json
     */
    public function getTransPackageList()
    {
        $trans_no = $this->request->get('trans_no', '');
        if(empty($trans_no)) {
            return json(['code' => 0, 'info' => '', 'data' => []]);
        }
        // 获取集运单信息
        $trans_info = TransporModel::mq()->where(['trans_no' => $trans_no])->find();
        if(empty($trans_info)) {
            return json(['code' => 0, 'info' => '', 'data' => []]);
        }

        $list = OrderExpressModel::mq()->where(['trans_id' => $trans_info['id']])->select()->toArray();
        $common_service   = CommonService::instance();
        // 获得仓库
        $warehouse_arr    = $common_service->getWarehouse($trans_info['account_id']);
        // 获得平台
        $system_platform  = $common_service->getSystemPlatform();
        // 获得公司名字
        $account          = $common_service->getAccount();

        foreach ($list as &$item) {
            $item['warehouse_name'] = $warehouse_arr[$item['warehouse_id']] ?? '';
//            $item['platform_name']  = $system_platform[$item['platform_id']]  ?? '';
            $item['account_name']   = $account[$item['account_id']]  ?? '';
            $item['status_name']    = OrderExpressModel::getStatus()[$item['status']] ?? '';
        }
        return json(['code' => 0, 'info' => '', 'data' => $list, 'count' => count($list)]);
    }

    /**
     * 确认发货
     * @auth true
     * @menu true
     * @return void
     */
    public function delivery()
    {
        $trans_ids = $this->request->post('trans_ids', 0);
        $list = TransporModel::mq()->whereIn('id', $trans_ids)->select()->toArray();

        if(empty($list)) {
            $this->error(lang('集运单信息错误'));
        }

        foreach ($list as $item) {
            if($item['status'] >= 3) {
                $this->error($item['trans_no'] . '--' . lang('该集运单已发货'));
            }
        }
        $result = TransporModel::mq()->whereIn('id', $trans_ids)->update(['status' => 3, 'delivery_at' => date('Y-m-d H:i:s')]);
        if($result) {
            $this->success(lang('发货成功'));
        } else {
            $this->error(lang('发货失败'));
        }
    }

    /**
     * 删除
     * @auth true
     * @menu true
     * @return void
     */
    public function delete($id)
    {
        $info = TransporModel::mq()->where(['id' => $id])->find();
        if(empty($info)) {
            $this->error(lang('集运单信息错误'));
        }
        // 已发货集运单不能删除
        if($info['status'] >= 3) {
            $this->error(lang('集运单已发货不能删除'));
        }

        // 启动事务
        Db::startTrans();
        try {
            // 更新包裹信息
            $is_update = OrderExpressModel::mq()->where(['trans_id' => $id])->update(['trans_id' => 0]);
            if($is_update) {
                TransporModel::mq()->where(['id' => $id])->delete();
            } else {
                $this->error(lang('删除失败'));
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error(lang('删除失败') . '：' . $e->getMessage());
        }
        $this->success(lang('删除成功'));
    }

    /**
     * 打印标签
     * @return void
     */
    public function printLabel()
    {
        $trans_no = $this->request->post('trans_no', '');
        $auto_name = $this->request->post('auto_name', '');
        if(empty($trans_no)) {
            $this->error(lang('请先生成或者搜索集运单号'));
        }
        $trans_info = TransporModel::mq()->where(['trans_no' => $trans_no])->find();
        if(empty($trans_info)) {
            $this->error(lang('请先生成或者搜索集运单号'));
        }

        TransporModel::mq()->where(['id' => $trans_info['id']])->update(['tag' => $auto_name]);

        // 获取集运单下的包裹
        $list = OrderExpressModel::mq()->where(['trans_id' => $trans_info['id']])->select()->toArray();
        $data = [
            'package_num' => count($list),
            'weight' => 0,
            'trans_no' => $trans_no,
            'auto_name' => $auto_name,
        ];
        foreach ($list as $item) {
            $data['weight'] += $item['weight'] ?? 0;
        }
        $this->success(lang('打印成功'), $data);
    }

    /**
     * 打包集运单
     * @return void
     */
    public function packTrans()
    {
        $trans_no = $this->request->post('trans_no', 0);

        if(empty($trans_no)) {
            $this->error(lang('请先生成或者搜索集运单号'));
        }
        $trans_info = TransporModel::mq()->where(['trans_no' => $trans_no])->find();
        if(empty($trans_info)) {
            $this->error(lang('请先生成或者搜索集运单号'));
        }

        $result = TransporModel::mq()->where(['id' => $trans_info['id']])->update(['status' => 2]);
        if($result) {
            $this->success(lang('打包成功'));
        } else {
            $this->error(lang('打包失败'));
        }

    }


}
?>